#include "stdio.h"
#include "stdlib.h"
#include <sys/socket.h>
#include <netinet/in.h>

#define MAX_BUFF 4096

int main()
{
    int sockfd, n, i;
    char recvline[MAX_BUFF + 1];
    struct sockaddr_in servaddr;
    char buff[]="showport\r";
    FILE *fp = NULL;

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        fprintf(stderr, "Socket error\n");
        return -2;
    }

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(10000);
    if (inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr) <= 0)
    {
        fprintf(stderr, "inet_pton error\n");
        return -3;
    }

    if (connect (sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    {
        fprintf(stderr, "connect error\n");
        return -4;
    }

    for(;;)
    {
        sendto(sockfd, buff, sizeof(buff), 0, (struct sockaddr *)&servaddr, sizeof (servaddr));        
        fp = fopen("/var/www/html/showport", "w");
        if (NULL == fp)
        {
            fprintf(stderr, "Open file error\n");
            return -1;
        }

        while(1)
        {               
            memset(recvline, 0x0, sizeof (recvline));
            n = recvfrom (sockfd, recvline, sizeof(recvline), 0, NULL, NULL);
            fputs(recvline, fp);

            if ((n < MAX_BUFF) && (n > 100)) /* Cheat to break out while loop */
                break;
        }
        fclose(fp);
        sleep(1);
    }

    return 0;
}
